import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import '../../pull_down_button.dart';
import '../items/divider.dart';
import 'blur.dart';

/// 下拉菜单容器
@immutable
@internal
class MenuDecoration extends StatelessWidget {
  const MenuDecoration({
    super.key,
    required this.child,
    required this.backgroundColor,
    required this.borderRadius,
  });

  final Widget child;

  final Color backgroundColor;

  final BorderRadius borderRadius;

  @override
  Widget build(BuildContext context) {
    Widget box = ColoredBox(
      color: backgroundColor,
      child: child,
    );

    if (BlurUtils.useBackdropFilter(backgroundColor)) {
      box = BackdropFilter(
        filter: BlurUtils.menuBlur(context),
        child: box,
      );
    }

    return ClipRSuperellipse(
      borderRadius: borderRadius,
      child: box,
    );
  }
}

/// 下拉菜单项可滚动主体内容
@immutable
@internal
class MenuBody extends StatefulWidget {
  const MenuBody({
    super.key,
    required this.items,
    required this.scrollController,
  });

  final List<PullDownMenuEntry> items;

  final ScrollController? scrollController;

  @override
  State<MenuBody> createState() => _MenuBodyState();
}

class _MenuBodyState extends State<MenuBody> {
  late final ScrollController _effectiveScrollController;

  @override
  void initState() {
    super.initState();
    _effectiveScrollController = widget.scrollController ?? ScrollController();
  }

  @override
  void dispose() {
    _effectiveScrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final child = CupertinoScrollbar(
      controller: _effectiveScrollController,
      child: SingleChildScrollView(
        primary: false,
        clipBehavior: Clip.none,
        controller: _effectiveScrollController,
        child: ListBody(
          children: MenuSeparator.wrapVerticalList(widget.items),
        ),
      ),
    );

    return Semantics(
      scopesRoute: true,
      namesRoute: true,
      explicitChildNodes: true,
      label: 'Pull-Down menu',
      child: switch (defaultTargetPlatform) {
        TargetPlatform.android || TargetPlatform.iOS => child,
        _ => ScrollConfiguration(
            behavior:
                ScrollConfiguration.of(context).copyWith(scrollbars: false),
            child: child,
          ),
      },
    );
  }
}
